<?php
/**
 * Created by PhpStorm.
 * User: 董坤鸿
 * Date: 2017/1/10
 * Time: 下午3:59
 */

namespace EWeiLink\JuPai\Services;

use EWeiLink\JuPai\Contact;
use EWeiLink\JuPai\JuPai;
use EWeiLink\JuPai\Message;
use EWeiLink\JuPai\Planner;
use Cache;

class MessageService
{
    /**
     * 监听消息
     * @param $plannerId    //理财师ID
     * @param $time     //读取消息的时间
     * @return array
     */
    public function listen($plannerId, $time)
    {
        $cache_key = "{$plannerId}:preReadTime";
        $preReadTime = is_null($time) ? Cache::get($cache_key, $time) : $time; // TODO debug
        $contactsIds = Contact::where(['plannerId' => $plannerId])->pluck('_id');
        $contacts = [];
        $messages = [];
        $createTime = '';
        if ($preReadTime) { //有读取消息时间
            $messageHandler = Message::whereIn('from', $contactsIds)->where('createTime', '>', intval($preReadTime))->get();
        } else {
            //没有读取时间就默认取10条
            $messageList = Message::whereIn('from', $contactsIds)->limit(10)->orderBy('_id', 'DESC')->get();
            $messageHandler = $messageList->sortBy('_id');
        }
        foreach ($messageHandler as $message){
            if (isset($message->type) && $message->type === 'verify_msg') {
                $contact = Contact::find($message->from);
                $contact->createTime = $message->createTime;
                if($contact){
                    array_push($contacts, $contact);
                }
            }
            array_push($messages, $message);
            //取出最大的创建时间
            $createTime = $createTime < ($message->createTime) ? $message->createTime : $createTime;
        }
        if (count($contacts) > 0 OR count($messages) > 0) {
            Cache::forever($cache_key, $time); // TODO debug
        }
        //处理lastTime
        $lastTime = $messages ? $createTime : time();
        return compact('contacts', 'messages', 'lastTime');
    }

    /**
     * 发送消息
     * @param $plannerId //理财师ID
     * @param $content  //消息内容
     * @param $to   //联系人的ID
     * @param string $type  //消息类型
     * @return bool
     */
    public function send($plannerId, $content, $to, $type = 'text_msg')
    {
        $ret = false;
        if (is_array($to)) {
            foreach ($to as $key => $contactsId) {
                $message = $this->getMessages($plannerId, $content, $contactsId, $type);
                $result = $this->sendMessage($message);
                $ret = ($ret or $result);
            }
        } else {
            $message = $this->getMessages($plannerId, $content, $to, $type);
            $ret = $this->sendMessage($message);
        }
        if($ret){
            return true;
        }
        return false;
    }

    /**
     * 获取消息内容
     * @param $plannerId  //理财师ID
     * @param $content  //消息内容
     * @param $to   //联系人的ID
     * @param string $type  //消息类型
     * @return mixed
     */
    protected function getMessages($plannerId, $content, $to, $type)
    {
        $contacts = Contact::find($to);
        if ($contacts && $contacts->wechatInfo && intval($contacts->plannerId) === intval($plannerId)) {
            $message = new Message;
            $message->clientUin = $contacts->clientUin;     //clientUin
            $message->content = $content;   //消息内容
            $message->type = $type; //消息类型
            $message->to = $to;  //联系人ID
            $message->createTime = time();  //发送消息时间
            return $message;
        } else {
            return false;
        }
    }

    /**
     * 发送具体消息
     * @param $message
     * @return bool
     */
    public function sendMessage($message){
        $service = JuPai::makeBridgeClass('App\Plugins\Wechat\Messages', [$message['clientUin']]);
        if (!is_null($service)) {
            $results = $service->send($message->getMessageArray());
            if ($results) {
                $message->save();
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 查询单个理财师
     * @param $plannerId
     */
    public function findByPlannerId($plannerId)
    {
        $planner = Planner::find($plannerId);
        assert($planner,  'Not found Planner');

    }

    /**
     * 钜派 检查是否允许指定微信号添加指定微信账号的联系人
     * @param int $clientUin
     * @param string $account
     * @param string $content
     * @return boolean
     **/
    public function checkVerifyMsg($clientUin, string $account, string $content)
    {
        // 检查validCode
        if (is_numeric($content) && strlen($content) === 6) {
            if (JuPai::callBridgeHelper('checkCrcNumber', [$content])) {
                $validCode = intval(substr($content, 0, strlen($content) - 1));
                /** @var Planner $planner */
                $planner = Planner::byValidCode($validCode)->first();
                // 理财师存在，查看用户是否已经是理财师的好友
                if ($planner) {
                    $contactExists = $planner
                        ->contacts()
                        ->findByAccount($account)
                        ->where('clientUin', '<>', $clientUin)
                        ->exists();
                    return !$contactExists;
                }
            }
        }
        return false;
    }

    /**
     * 添加钜派的新消息
     * @param $newMsg
     * @return Message|null
     */
    public function handleNewMsg($newMsg)
    {
        // 将新消息的from改成contactId
        if (!empty($newMsg->from)) {
            $contact = Contact::clientUin($newMsg->clientUin)->ewlinkId($newMsg->from)->first();
            if (!$contact) {
                // 检查是否是好友请求
                if ($newMsg->type === 'verify_msg') {
                    $content = $newMsg->recommendInfo->Content;
                    $validCode = strlen($content) > 5 ? substr($content, 0, 5) : $content;
                    /** @var Planner $planner */
                    $planner = Planner::byValidCode(intval($validCode))->first();
                    $plannerId = is_null($planner) ? 0 : $planner->plannerId;
                    if (!Contact::where([
                        'ewlink_id' => $newMsg->from,
                        'clientUin' => $newMsg->clientUin,
                        'plannerId' => $plannerId
                    ])->exists()) {
                        $contact = Contact::create([
                            'clientUin' => $newMsg->clientUin,
                            'plannerId' => $plannerId,
                            'customerId' => 0,
                            'ewlink_id' => $newMsg->from,
                        ]);
                    }
                } else {
                    return null; // 联系人不存在
                }
            }
            if (!Message::where('msgId', $newMsg->msgId)->exists()) {
                /** @var Message $message */
                $message = Message::create([
                    'clientUin' => $newMsg->clientUin,
                    'msgId' => $newMsg->msgId,
                    'from' => $contact->id,
                    'type' => $newMsg->type,
                    'content' => ($newMsg->type === 'verify_msg')
                        ? $newMsg->recommendInfo->Content : $newMsg->content,
                    'createTime' => time()  // 使用入库时间，减少丢消息概率
                ]);
                return $message;
            }
        }
        return null;
    }
}